import React, { useRef, useEffect, useState } from 'react';
import ReactEcharts from 'echarts-for-react';
import { Radio, Button } from 'antd';
import {
    FileExcelOutlined,
    FileImageOutlined,
    PieChartOutlined,
    BarChartOutlined,
    LineChartOutlined,
} from '@ant-design/icons';
import XLSX from 'xlsx';
import html2canvas from 'html2canvas';
import { downloadExcel } from '@/pages/utils/array';
import style from './CustomDatePicker.css';
import IndexStyle from '@/pages/IndexPage.css';
import CustomDatePicker from './CustomDatePicker';
import Loading from '@/pages/components/Loading';

function EnergyCostTrend({ item, theme, onDispatch }) {
    const echartsRef = useRef();
    const [dataType, setDataType] = useState('cost');
    const [sourceData, setSourceData] = useState({});
    const [loading, setLoading] = useState(false);
    let textColor = '#58586f';
    let seriesData = [];
    useEffect(() => {
        setLoading(true);
        new Promise((resolve, reject) => {
            onDispatch({ type: 'board/fetchSingleEnergyCost', payload: { resolve, reject, timeType: '2' } })
        })
        .then((data) => {
            setSourceData({ cost: data.cost, date: data.date, energy: data.energy });
            setLoading(false);
        })
    }, []);

    seriesData.push({
        type: 'line',
        symbolSize: 6,
        name: dataType === 'cost' ? '成本' : '能耗',
        showSymbol: false,
        data: sourceData[dataType] || [],
        lineStyle: {
            color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [
                    {
                        offset: 0,
                        color: '#44e6ff', // 0% 处的颜色
                    },
                    {
                        offset: 1,
                        color: '#7348fa', // 100% 处的颜色
                    },
                ],
                global: false, // 缺省为 false
            }
        },
        itemStyle: {
            color: '#7348fa',
        },
        areaStyle: {
            opacity: 0.15,
            color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                    offset: 0, color: 'rgba(34, 229, 255, 0.85)' // 0% 处的颜色
                }, {
                    offset: 1, color: 'rgba(34, 229, 255, 0.15)' // 100% 处的颜色
                }],
                global: false // 缺省为 false
            },
        }
    })

    return (
        <div className={IndexStyle['card-container']} style={{ boxShadow: 'none' }}>
            { loading && <Loading /> }
            <div
                className={IndexStyle['card-title']}
                style={{ height: '3rem', borderBottom:'none', lineHeight:'unset' }}
            >
                <div style={{ display: 'flex', alignItems:'center' }}>
                    <span style={{ marginRight: '1rem', color: theme === 'dark' ? '#fff' : '#000' }}>能耗成本趋势</span>
                    <CustomDatePicker
                        theme={theme}
                        onDispatch={(action)=>{
                            setLoading(true);
                            new Promise((resolve, reject) => {
                                onDispatch({ type: 'board/fetchSingleEnergyCost', payload: { resolve, reject, timeType:action.timeType } })
                            })
                            .then((data) => {
                                setSourceData({ cost: data.cost, date: data.date, energy: data.energy });
                                setLoading(false);
                            })
                        }}
                    />
                    <Radio.Group className={style['custom-radio'] + ' ' + ( theme === 'dark' ? style['dark'] : '')} value={dataType} onChange={e=>setDataType(e.target.value)}>
                        <Radio.Button value='cost'>成本</Radio.Button>
                        <Radio.Button value='energy'>能耗</Radio.Button>
                    </Radio.Group>
                </div>
                {/* <Radio.Group
                    size="small"
                    onChange={(e) => {
                        let value = e.target.value;
                        let fileTitle = chartMaps[item.key];
                        if (value === 'bar' || value === 'line' || value === 'pie') {
                            setChartType(value);
                        }
                        if (value === 'download' && echartsRef.current) {
                            html2canvas(echartsRef.current.ele, {
                                allowTaint: false,
                                useCORS: false,
                                backgroundColor: '#fff',
                            }).then((canvas) => {
                                let MIME_TYPE = 'image/png';
                                let url = canvas.toDataURL(MIME_TYPE);
                                let linkBtn = document.createElement('a');
                                linkBtn.download = fileTitle;
                                linkBtn.href = url;
                                let event;
                                if (window.MouseEvent) {
                                    event = new MouseEvent('click');
                                } else {
                                    event = document.createEvent('MouseEvents');
                                    event.initMouseEvent(
                                        'click',
                                        true,
                                        false,
                                        window,
                                        0,
                                        0,
                                        0,
                                        0,
                                        0,
                                        false,
                                        false,
                                        false,
                                        false,
                                        0,
                                        null,
                                    );
                                }
                                linkBtn.dispatchEvent(event);
                            });
                        }
                        if (value === 'excel') {
                            var aoa = [],
                                thead = ['成本类型', '单位'];
                            categoryData.map((i) => thead.push(i));
                            aoa.push(thead);
                            seriesData.forEach((item) => {
                                let temp = [];
                                temp.push(item.name, '元', ...item.data);
                                aoa.push(temp);
                            });

                            var sheet = XLSX.utils.aoa_to_sheet(aoa);
                            sheet['!cols'] = thead.map((i) => ({ wch: 16 }));
                            downloadExcel(sheet, fileTitle + '.xlsx');
                        }
                    }}
                >
                    <Radio.Button value="pie">
                        <PieChartOutlined />
                    </Radio.Button>
                    <Radio.Button value="bar">
                        <BarChartOutlined />
                    </Radio.Button>
                    <Radio.Button value="line">
                        <LineChartOutlined />
                    </Radio.Button>
                    <Radio.Button value="excel">
                        <FileExcelOutlined />
                    </Radio.Button>
                    <Radio.Button value="download">
                        <FileImageOutlined />
                    </Radio.Button>
                </Radio.Group> */}
            </div>
            <div
                className={IndexStyle['card-content']}
                style={{ height: 'calc( 100% - 3rem)' }}
            >
                <ReactEcharts
                    ref={echartsRef}
                    style={{ height: '100%' }}
                    notMerge={true}
                    option={{
                        tooltip: {
                            trigger: 'axis',
                        },
                        grid: {
                            top: 40,
                            left: 20,
                            right: 20,
                            bottom: 10,
                            containLabel: true,
                        },
                        xAxis: {
                            type: 'category',
                            data: sourceData.date || [],
                            silent: false,
                            splitLine: {
                                show: false,
                            },
                            splitArea: {
                                show: false,
                            },
                            axisLabel: {
                                show: true,
                                color: textColor,
                            },
                            axisTick: { show: false },
                            axisLine: { show: true, lineStyle: { color: textColor } },
                        },
                        yAxis: {
                            type: 'value',
                            splitArea: {
                                show: false,
                            },
                            name: dataType === 'cost' ? '元' : 'kwh',
                            nameTextStyle:{ color:textColor },
                            axisLine: { show: false },
                            axisTick: { show: false },
                            splitLine: {
                                show: true,
                                lineStyle : { color: theme === 'dark' ? '#313143' : '#f7f7f7' }
                            },
                            axisLabel: {
                                show: true,
                                color: textColor,
                            },
                        },
                        series: seriesData,
                    }}
                />
            </div>
        </div>
    );
}

export default EnergyCostTrend;
